﻿using System;
using HongYeSystemWebApi.Templet.Core;
using HongYeSystemWebApi.Templet.Service;
using HongYeSystemWebApi.Templet.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using static HongYeSystemWebApi.Templet.Entity.Model.CommonInfo;
using System.Threading.Tasks;
using HongYeSystemWebApi.Templet.Entity.ApiResult;
using System.Collections.Generic;
using HongYeSystemWebApi.Templet.Entity.Entities;
using Newtonsoft.Json.Linq;
using HongYeSystemWebApi.Templet.Entity.Request.SysSupplier;
using OfficeOpenXml;
using System.Drawing.Drawing2D;


// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HongYeSystemWebApi.Templet.Controllers
{
  
    //[Authorize] //为类中所有方法添加认证
    public class ValuesController : BaseController
    {
        private readonly SqlSugarClient _db;

        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="db"></param>
        public ValuesController(IHelpDB db)
        {
            this._db = db.OpenDB();
            //_account = new Account();

        }

        /// <summary>
        /// 测试Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetData(int abc)
        {
            LogHelp.LogInfo("GetData:" + abc);
            return Ok(new ResultInfo() { Data = "GetData:"+ abc });
        }

        /// <summary>
        /// 测试Post
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostData([FromBody]string data)
        {
            return Ok(new ResultInfo() { Data="PostData:"+ data });
        }

        /// <summary>
        /// 测试Delete
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DeleteData()
        {
            return Ok(new ResultInfo() { Data = "PostData" });
        }

        /// <summary>
        /// 自动生成数据库映射表
        /// </summary>
        [HttpGet]
        public IActionResult AutoCreaterEntity()
        {
            // 直接生成数据库所有实体类，并识别自增长ID 生成类的文件夹地址D:\xxx\DbModels 生成类的命名空间 xxx_Entity
            //_db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\Item\VS\Gitee\HongYeSystemWebApi.Templet\HongYeSystemWebApi.Templet.Entity", "HongYeSystemWebApi.Templet.Entity");
            //生成数据库单个表的实体类，并识别自增长ID  生成类的文件夹地址D:\xxx\DbModels 生成类的命名空间 xxx_Entity

            _db.DbFirst.IsCreateAttribute().Where("Account").CreateClassFile(@"D:\Item\VS\Gitee\HongYeSystemWebApi.Templet\HongYeSystemWebApi.Templet.Entity", "HongYeSystemWebApi.Templet.Entity");

            return Ok();
        }

        /// <summary>
        /// 测试Post
        /// </summary>
        /// <returns></returns>
        [Authorize]//单个方法添加认证 可以为整个Controller 添加认证 （在类上添加同样标记）  单个不需要认证 添加[AllowAnonymous] 标记
        [HttpPost]
        public IActionResult TestAuthorize([FromBody] string data)
        {
            //获取认证信息
            var userID = Convert.ToInt32(User.FindFirst("UserID").Value);
            var userName = User.FindFirst("UserName").Value;
            var roles = User.FindFirst("Roles").Value;

            return Ok(new ResultInfo() { Data = "PostData:" + data + " UserInfo：" + JsonConvert.SerializeObject(new { UserID = userID, UserName = userName, Roles = roles }) });
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult>  Login([FromBody] JwtUserInfo userInfo)
        {
            #region 登录逻辑
            //编写登录业务逻辑

            var  data=_db.Queryable<Entity.Users>().ToList();

            var user=await _db.Queryable<Entity.Users>().FirstAsync(x => x.UserName == userInfo.UserName);
            if (user == null)
            {
                return ApiResult.False("当前帐号不存在");
            }
            if(user.PassWord != userInfo.PassWord) {
                return ApiResult.False("当前帐号密码不正确");
            }
            #endregion
            //根据用户信息生成Token
            var generateJwt = new GenerateJwt();
            string token;
            try
            {
                token = generateJwt.GenerateEncodedToken(userInfo.UserName, userInfo);
            }
            catch (Exception e)
            {
                LogHelp.LogError("CreateJWT ERROR:" + e.Message + "/r/n 请求源数据:" + JsonConvert.SerializeObject(userInfo));
                return ApiResult.False("程序出错了");
            }
            //返回用户信息及token
              return ApiResult.True(new { dat= user, token= token }) ;
        }


        [HttpPost]
        public async Task<ApiResult> UpPassWord([FromBody] SysUserUpdataRequest user)
        {
            var result = await _db.Queryable<Entity.Users>().FirstAsync(x => x.Id == user.id);
            if (result == null)
                throw new Exception("程序错误");
            else if (result.PassWord != user.OldPassword)
            {
                throw new Exception("初始秘密 错误请验证后输入");
            }
            result.PassWord = user.NewPassword;
            await _db.Updateable(result).WhereColumns(it => new { it.Id }).ExecuteCommandAsync();
            return ApiResult.True("密码修改成功");
        }
        #region Account CRUD Demo 详细文档：http://www.codeisbug.com/Doc/8/1121

        /// <summary>
        /// 获取银行卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetBankinfo()
        {
            var result = await _db.Queryable<Entity.Entities.Bankinfo>().Where(x => !x.Delete).ToListAsync();
            return ApiResult.True(new { Data = result });
        }
        /// <summary>
        /// 获取公司
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetCompany()
        {
            var result = await _db.Queryable<Entity.Entities.CompanyEntity>().Where(x=>!x.Delete).ToListAsync();
            return ApiResult.True(new { Data = result });
        }



        /// <summary>
        /// 类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetCostType()
        {
            var result = await _db.Queryable<Entity.Entities.CostType>().Where(x => !x.Delete).ToListAsync();
            return ApiResult.True(new { Data = result });
        }

        /// <summary>
        /// 项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetProject()
        {
            var result = await _db.Queryable<Entity.Entities.ProjectEntity>().Where(x => !x.Delete).ToListAsync();
            return ApiResult.True(new { Data= result });
        }
        /// <summary>
        /// 供应商
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetSupplier()
        {
            var result = await _db.Queryable<Entity.Entities.Supplier>().Where(x => !x.Delete).ToListAsync();
            return ApiResult.True(new { Data = result });
        }


        [HttpPost]
        public async Task<ApiResult> setDate()
        {

            var result = await _db.Queryable<HongYeSystemWebApi.Templet.Entity.Entities.Expenditure>().Where(x => !x.Delete).ToListAsync();
            foreach (var item in result)
            {
             
             var data=   item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
             var datatime= item.CreateDate.ToString("HH:mm:ss");
             var data1 = item.OperatDate.Value.ToString("HH:mm:ss");
             data=data.Replace(datatime, data1);
                item.CreateDate = Convert.ToDateTime(data);
            }

            await _db.Updateable(result).WhereColumns(it => new { it.Id }).ExecuteCommandAsync();
            return ApiResult.True(new { Data = result });
        }
        #endregion

    }
}
